package com.sdkx.wear_os.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.net.*
import android.os.Build
import android.text.TextUtils
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStreamReader
import java.util.*


/**
 * 获取应用程序名称
 */
@Synchronized
fun getAppName(context: Context): String? {
    try {
        val packageManager = context.packageManager
        val packageInfo = packageManager.getPackageInfo(
            context.packageName, 0
        )
        val labelRes = packageInfo.applicationInfo.labelRes
        return context.resources.getString(labelRes)
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return null
}

/**
 * 获取应用程序版本名称信息
 */
@Synchronized
fun getVersionName(context: Context?): String {
    try {
        val packageManager = context?.packageManager
        val packageInfo = packageManager?.getPackageInfo(
            context.packageName, 0
        )
        return packageInfo?.versionName.toString()
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return ""
}


/**
 * 获取应用程序版本code信息
 */
@RequiresApi(Build.VERSION_CODES.P)
@Synchronized
fun getVersionCode(context: Context): Long {
    try {
        val packageManager = context.packageManager
        val packageInfo = packageManager.getPackageInfo(
            context.packageName, 0
        )
        return packageInfo.longVersionCode
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return 0
}


/**
 * 获取应用程序包名信息
 */
@Synchronized
fun getPackageName(context: Context): String? {
    try {
        val packageManager = context.packageManager
        val packageInfo = packageManager.getPackageInfo(
            context.packageName, 0
        )
        return packageInfo.packageName
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return null
}


/**
 * 获取图标 bitmap
 */
@Synchronized
fun getBitmap(context: Context): Bitmap? {
    var packageManager: PackageManager? = null
    var applicationInfo: ApplicationInfo? = null
    try {
        packageManager = context.applicationContext
            .packageManager
        applicationInfo = packageManager.getApplicationInfo(
            context.packageName, 0
        )
    } catch (e: PackageManager.NameNotFoundException) {
        applicationInfo = null
    }
    val d = applicationInfo?.let { packageManager!!.getApplicationIcon(it) } //xxx根据自己的情况获取drawable
    val bd = d as BitmapDrawable
    return bd.bitmap
}

/**
 * 判断当前应用是否是debug状态
 */
fun isApkInDebug(context: Context): Boolean {
    return true
    return try {
        val info: ApplicationInfo = context.applicationInfo
        info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
    } catch (e: java.lang.Exception) {
        false
    }
}

/**
 * 安装apk
 */
fun installApk(context: Activity, file: File) {
    val intent = Intent(Intent.ACTION_VIEW)
    val contentUri: Uri =
        FileProvider.getUriForFile(context, "${getPackageName(context)}.provider", file)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
    context.startActivity(intent)
}

/**
 * 安装apk
 */
fun installApk2(context: Activity, file: File) {
    val intent = Intent(Intent.ACTION_VIEW)
    val contentUri: Uri = file.toUri()
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
    context.startActivity(intent)
}


/**
 * 判断某个界面是否在前台
 *
 * @param context   Context
 * @param className 界面的类名
 * @return 是否在前台显示
 */
fun isForeground(context: Context?): Boolean {
    val className = context?.javaClass?.name
    if (context == null || TextUtils.isEmpty(className)) return false
    val am: ActivityManager =
        context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val list: List<ActivityManager.RunningTaskInfo> = am.getRunningTasks(1)
    if (list.isNotEmpty()) {
        val cpn: ComponentName? = list[0].topActivity
        if (cpn != null) {
            if (className == cpn.className) return true
        }
    }
    return false
}

/**
 * 判断 APP 是否安装  需要在清单文件中声明  SDK检测虚拟机
 *  <queries>
 *      <package android:name="com.baidu.BaiduMap" />
 *      <package android:name="com.autonavi.minimap" />
 *      <package android:name="com.tencent.map" />
 *  </queries>
 * @param packageName 需要检查的应用包名
 * @return
 */
fun isInstalled(packageName: String): Boolean {
    try {
        val process = Runtime.getRuntime().exec("pm list package -3")
        val bis = BufferedReader(InputStreamReader(process.inputStream))
        var line: String? = null
        while (bis.readLine().also { line = it } != null) {
            println("MainActivity.runCommand, line=" + line!!.substring(8, line!!.length))
            if (packageName == line!!.substring(8, line!!.length)) {
                return true
            }
        }
    } catch (e: IOException) {
        println("MainActivity.runCommand,e=$e")
    }
    return false
}

/**
 * 应用内实现国际化操作
 */
fun attachBaseContext(context: Context, locale: Locale): Context {
    //7.0及以后
    return updateResources(context, locale)
}

private fun updateResources(context: Context, locale: Locale): Context {
    val resources: Resources = context.resources
    val configuration: Configuration = resources.configuration
    configuration.setLocale(locale)
    return context.createConfigurationContext(configuration)
}

/**
 * 重启应用
 */
fun restartApp(context: Context) {
    val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
    intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    context.startActivity(intent)
}
